package com.yuuzy.qqserver.service;

import com.yuuzy.qqcommon.Message;
import com.yuuzy.qqcommon.MessageType;
import com.yuuzy.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.Objects;
import java.util.Scanner;

public class SendNewsToAllService implements Runnable {

	@Override
	public void run() {
		while (true) {
			System.out.println("请输入您要推送的新闻/消息［输入exit表示退出推送服务］");
			String news = Utility.readString(1000);
			if ( Objects.equals(news, "exit")) {
				break;
			}
			Message message = new Message();
			message.setSender("服务器");
			message.setContent(news);
			message.setSendTime(new Date().toString());
			message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
			System.out.println("服务器给所有人说：" + news);

			//遍历当前所有线程，得到socket，并发送message
			String[] key = ManageClientThreads.getOnlineUsers().split(" ");
			for (int i = 0; i < ManageClientThreads.getLiveNumber(); i++) {
				ServerConnectClientThread serverConnectClientThread = ManageClientThreads.getServerConnectClientThread(key[i]);
				//转发给指定客户端
				ObjectOutputStream objectOutputStream = null;
				try {
					objectOutputStream = new ObjectOutputStream(serverConnectClientThread.socket.getOutputStream());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
				try {
					objectOutputStream.writeObject(message);
				} catch (IOException e) {
					throw new RuntimeException(e);
				}

			}
		}
	}

}
